<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>栈的封装</title>
</head>

<body>
    <script>
        //封装栈类
        function Stack() {
            //栈中的属性
            this.items = [];

            //栈的相关操作(方法)

            //1.将元素加入栈
            //this.push = function(){} //给对象的实例添加方法
            Stack.prototype.push = function (element) {
                this.items.push(element);
            }//给整个类添加方法


            //2.从栈中取出元素
            Stack.prototype.pop = function () {
                return this.items.pop();
            }

            //3.查看栈顶元素
            Stack.prototype.peek = function () {
                return this.items[this.items.length - 1];
            }

            //4.判断栈是否为空
            Stack.prototype.isEmpty = function () {
                return this.items.length == 0;
            }

            //5.获取栈中元素的个数
            Stack.prototype.size = function () {
                return this.item.length;
            }

            //6.toString方法
            Stack.prototype.toString = function () {
                var resultString = ''
                for (var i = 0; i < this.items.length; i++) {
                    resultString += this.items[i] + ' ';
                }
                return resultString;
            }
        }

        //栈的使用
        // var s = new Stack();
        // s.push();//压栈
        // s.pop();//出栈
 
        //十进制转二进制函数
        function dec2bin(decNumber) {
            //1.定义栈对象
            var stack = new Stack();

            //2.循环操作
            while (decNumber > 0) {
                //获取余数放入栈中
                stack.push(decNumber % 2)
                //获取整除后的结果作为下一次运算的数字
                decNumber = Math.floor(decNumber / 2)
            }

            //3.从栈中取出0和1
            var binaryString = '';
            while (!stack.isEmpty()) {
                binaryString += stack.pop();
            }
            return binaryString;
        }

        alert(dec2bin(100));
    </script>
</body>

</html>